import type { server_info } from 'serve/actions/apis'
import { Fetch } from '../utils/ajax'

export type ServerInfo = ReturnType<typeof server_info> extends Promise<infer R> ? R : never

export const api_system = {
    /** 获取服务器信息 */
    server_info: (
        onMessage: (message: ServerInfo) => void
    ) => {
        let sse: EventSource
        function visibilityChange () {
            if (document.hidden) {
                if (!!sse) sse.close();
                sse = null
            } else  {
                sse = new EventSource('/api/server/info')
                sse.addEventListener('message', function (e) {
                    e.data && onMessage(JSON.parse(e.data))
                })
            }
        };
        document.addEventListener("visibilitychange", visibilityChange, false);
        visibilityChange();
        return sse;
    },
    /** 关闭服务器 */
    shutdown: () => Fetch('/api/server/shutdown'),
}